package starpay

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/starpay/starpay"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Starpay{
		Url:        config.Url,
		MerchantId: config.MerchantId,
		SecretKey:  config.SecretKey,
	}
}

type Starpay struct {
	MerchantId string
	SecretKey  string
	Url        string
}
type Params struct {
	MerchantRef string `json:"merchant_ref"`
	Product     string `json:"product"`
	Amount      string `json:"amount"`
	Extra       extra  `json:"extra"`
}
type extra struct {
	FiatCurrency string `json:"fiat_currency"`
}
type Resp struct {
	Code      string `json:"code"`
	Timestamp int64  `json:"timestamp"`
	Message   string `json:"message"`
	Params    data   `json:"params"`
}
type data struct {
	MerchantRef  string    `json:"merchant_ref"`
	SystemRef    string    `json:"system_ref"`
	Amount       string    `json:"amount"`
	Fee          string    `json:"fee"`
	Status       int       `json:"status"`
	SuccessTime  int       `json:"success_time"`
	Payurl       string    `json:"payurl"`
	ExtendParams string    `json:"extend_params"`
	Product      string    `json:"product"`
	Extra        respextra `json:"extra"`
}
type respextra struct {
	Address string `json:"address"`
}

// 代收订单创建
func (star *Starpay) Pay(ctx context.Context, req map[string]any) (resp base.PayResponse, err error) {
	orderID := req["orderNo"].(string)
	amount := fmt.Sprintf("%.2f", req["amount"])
	payResult, err := starpay.StarPay(star.Url, star.MerchantId, orderID, star.SecretKey, amount)
	if err != nil {
		return resp, err
	}
	var result data
	err = json.Unmarshal([]byte(payResult.Params), &result)
	if err != nil {
		return resp, err
	}
	resp = base.PayResponse{
		Url:     result.Payurl,
		Address: result.Extra.Address,
		OrderNo: result.MerchantRef,
		Result:  payResult.Params,
	}
	return resp, nil

}
